package com.segersten.kalaha

class GameScoreController {

    def index = { }
	
	def leaderBoard = { 
		
		List scores = null
		if ("day".equals(params.period)) {
			scores = PlayerScoreDay.findAll("select from PlayerScoreDay ps order by ps.score desc")
		} 
		else if ("week".equals(params.period)) {
			scores = PlayerScoreWeek.findAll("select from PlayerScoreWeek ps order by ps.score desc")
		} 
		else if ("total".equals(params.period)) {
			scores = PlayerScoreTotal.findAll("select from PlayerScoreTotal ps order by ps.score desc")
		} 
		else {
			response.status = 404
			render(text:"Not found")
			return
		}
		
		int maxAgeSeconds = getMaxAge(scores.size())
		
		
		response.setHeader("Cache-Control","max-age=" + maxAgeSeconds)
		render(contentType:"text/json") {
			leaderboard = array {
				for(b in scores) {
					player( name:b.name, score:b.score )
				}
			} 
		}
    }
	
	def daily = {
		List scores = PlayerScoreDay.findAll("select from PlayerScoreDay ps")
		scores.each { score -> 
			score.delete()
		}
		render(text : "OK")
    }
	
	def weekly = {
		List scores = PlayerScoreWeek.findAll("select from PlayerScoreWeek ps")
		scores.each { score -> 
			score.delete()
		}
		render(text : "OK")
	}
	
	private int getMaxAge(int size) {
		if (size<500) {
			return 10
		}
		if (size<2000) {
			return 30
		}
		if (size<10000) {
			return 120
		}
		return 300
    }
}
